package com.nanosn.coffeemaker.java;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * Represents a Java Class files on disk
 * @author selkhateeb
 */
public class JavaClass {

    private File javaFile;
    private File classFile;
    private String className;
    private URL[] URLs;

    public JavaClass(String className, URL... urls)
            throws URISyntaxException,
                   ClassNotFoundException {
        this.className = className.replace(".", "/");
        this.URLs = urls;
        this.setFiles();
    }

    public boolean isUpToDate() {
        //if any of the files does not exist then their not up to date
        if (!classFile.exists() || !javaFile.exists()) {
            return false;
        }
        return (javaFile.lastModified() < classFile.lastModified());
    }

    private void setFiles() throws URISyntaxException, ClassNotFoundException {
        for (URL url : this.getURLs()) {
            this.classFile = new File(new File(url.toURI()), className +
                                                             ".class");
            this.javaFile = new File(new File(url.toURI()), className +
                                                            ".java");
            if (classFile.exists() || javaFile.exists()) {
                break;
            }
        }
        if (!classFile.exists() && !javaFile.exists()) {
            throw new ClassNotFoundException(
                    "Cannot find [" + className.replace("/", ".") +
                    "] in any of the provided urls");
        }

        //Set the javaFile to null if it does not exist
        if (!this.javaFile.exists()) {
            this.javaFile = null;
        }
    }

    public URL[] getURLs() {
        return URLs;
    }

    public void setURLs(URL[] URLs) {
        this.URLs = URLs;
    }

    public File getClassFile() {
        return classFile;
    }

    public void setClassFile(File classFile) {
        this.classFile = classFile;
    }

    public String getClassName() {
        return className.replace("/", ".");
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public File getJavaFile() {
        return javaFile;
    }

    public void setJavaFile(File javaFile) {
        this.javaFile = javaFile;
    }
}
